<template>
  <div id="teamCardList">
    <van-card
        v-for="team in props.teamList"
        :title="`${team.name}`"
        :desc="team.description"
        :thumb="team.createUser.avatarUrl"
        @click-thumb="teamChat(team.id,team.name,team.hasJoin)"
    >
      <template #tags>
        <van-tag plain type="danger"
                 style="margin-right: 8px; margin-top: 8px">
          {{ teamStatusEnum[team.status] }}
        </van-tag>
      </template>
      <template #bottom>
        <div>{{ `已加入人数：${team.hasJoinNum}/${team.maxNum}` }}</div>
        <div v-if="team.expireTime">
          {{ '过期时间：' + team.expireTime }}
        </div>
        <div>{{ '创建时间：' + team.createTime }}</div>
      </template>
      <template #footer>
        <van-button size="small" plain type="primary"
                    v-if="team.userId !== currentUser?.id && !team.hasJoin"
                    @click="preJoinTeam(team)">加入队伍
        </van-button>
        <van-button v-if="team.userId == currentUser?.id" size="small"
                    plain type="primary" @click="doUpdateTeam(team.id)">更新队伍
        </van-button>
        <!--  仅加入可见 -->
        <van-button size="small" plain type="primary"
                    v-if="team.userId !== currentUser?.id && team.hasJoin"
                    @click="doQuitTeam(team.id)">退出队伍
        </van-button>
        <van-button v-if="team.userId == currentUser?.id" size="small"
                    plain type="danger" @click="doDeleteTeam(team.id)">解散队伍
        </van-button>
      </template>
    </van-card>
  </div>
  <Dialog v-model:show="showPasswordDialog" title="请输入密码"
          show-cancel-button @confirm="doJoinTeam" @cancel="doJoinCancel">
    <van-field v-model="password" placeholder="请输入密码"/>
  </Dialog>
</template>

<script setup lang="ts">

import {TeamUserVO} from "../models/teamUser";
import {teamStatusEnum} from "../constants/team.ts";
import myAxios from "../plugins/myAxios.ts";
import {ResponseResult} from "../models/resopnse";
import {Dialog, showFailToast, showSuccessToast, showToast} from "vant";
import {onMounted, ref} from "vue";
import {userType} from "../models/user";
import {useRouter} from "vue-router";
import {getCurrentUser} from "../services/user.ts";
import {chatScopeEnum} from "../constants/chat.ts";


const router = useRouter()

interface TeamCardListProps {
  teamList: TeamUserVO[]
}

const props = withDefaults(defineProps<TeamCardListProps>(), {
  // @ts-ignore
  teamList: [] as TeamUserVO[]
})

const showPasswordDialog = ref<boolean>(false)
const password = ref<string>('')
const joinTeamId = ref<number>(0)

const emit = defineEmits<{
  (e: 'listTeam'): void
}>()

const currentUser = ref<userType | null>()
onMounted(async () => {
  currentUser.value = await getCurrentUser()
})

const preJoinTeam = (team: TeamUserVO) => {
  joinTeamId.value = team.id
  if (team.status === 0) {
    doJoinTeam()
  } else {
    showPasswordDialog.value = true
  }
}

const doJoinCancel = () => {
  joinTeamId.value = 0
  password.value = ''
}

/**
 * 加入队伍
 */
const doJoinTeam = async () => {
  if (!joinTeamId.value) {
    return
  }
  const res: ResponseResult<boolean> = await myAxios.post('/team/join', {
    teamId: joinTeamId.value,
    password: password.value,
  })
  if (res.code === 0 && res.data) {
    showSuccessToast('加入成功')
    emit('listTeam')
    doJoinCancel()
  } else {
    showFailToast("加入失败")
    showToast(res.description ? `${res.description}` : '')
  }
}
/**
 * 更新队伍
 * @param id
 */
const doUpdateTeam = (id: number) => {
  router.push({
    path: '/team/update',
    query: {
      id,
    }
  })
}
/**
 * 退出队伍
 * @param teamId
 */
const doQuitTeam = async (teamId: number) => {
  const res: ResponseResult<boolean> = await myAxios.post('/team/quit', {
    teamId,
  })
  if (res.code === 0 && res.data) {
    emit('listTeam')
    showSuccessToast('退出成功')
    password.value = ''
  } else {
    showFailToast('操作失败')
    showToast(res.description ? res.description : res.message)
  }
}
/**
 * 解散队伍
 * @param id
 */
const doDeleteTeam = async (id: number) => {
  const res: ResponseResult<boolean> = await myAxios.post('/team/delete', {
    id,
  })
  if (res.code === 0 && res.data) {
    emit('listTeam')
    showSuccessToast('解散成功')
  } else {
    showFailToast('操作失败')
    showToast(res.description ? res.description : res.message)
  }
}

const teamChat = (id: number, name: string, hasJoin: boolean) => {
  if (!hasJoin) {
    return
  }
  router.push({
    path: '/chat',
    query: {
      id,
      name,
      scope: chatScopeEnum.TEAM_CHAT
    }
  })
}

</script>

<style scoped>
#teamCardList :deep(.van-image__img) {
  height: 128px;
  object-fit: unset;
}
</style>
